package com.cbh.amadeus.server.handler;

import com.cbh.amadeus.common.enums.MessageType;
import com.cbh.amadeus.common.protocol.AmadeusMessage;
import com.cbh.amadeus.common.protocol.AmadeusMessageProtocol;
import com.cbh.amadeus.common.protocol.AmadeusMessageWrap;
import com.cbh.amadeus.server.core.Publisher;
import com.cbh.amadeus.server.domain.ChannelModel;
import com.cbh.amadeus.server.utils.TopicChannelManage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ChenBiHui
 * @date 2025/4/25
 */
@Slf4j
public class RegisterHandler extends SimpleChannelInboundHandler<AmadeusMessageWrap> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AmadeusMessageWrap msg) {
        MessageType type = MessageType.find(msg.getType());
        if (type == MessageType.REGISTER) {
            Channel channel = ctx.channel();
            AmadeusMessage message = msg.getMessage();
            Publisher.DEFAULT.execute(() -> {
                TopicChannelManage.set(channel, message);
                ctx.writeAndFlush(registered(message))
                        .addListener(item -> {
                            if (item.isSuccess()) {
                                ChannelModel channelModel = TopicChannelManage.findModelWithChannel(channel);
                                log.info(
                                        "===== [REGISTER] Topic [{}] has been registered with [{} - {}] =====",
                                        message.getTopic(),
                                        message.getPayload(),
                                        channelModel == null ? "unknown" : channelModel.getOrigin()
                                );
                            }
                        });
            });
            return;
        }
        ctx.fireChannelRead(msg);
    }

    private AmadeusMessageWrap registered(AmadeusMessage message) {
        AmadeusMessageWrap answer = new AmadeusMessageWrap();
        answer.setMagic(AmadeusMessageProtocol.MAGIC);
        answer.setType(MessageType.REGISTERED.getType().byteValue());
        answer.setMessage(
                new AmadeusMessage()
                        .setProvider(message.getProvider())
                        .setTopic(message.getTopic())
                        .setPayload(message.getPayload())
        );
        return answer;
    }
}
